/**
 * 生猪运输台账
 * @constructor
 */
function PigAccount() {
}

PigAccount.init = function () {
    if ($("#k").val() == 2) {
        document.getElementById("toolbar").style.display = "none";
    }
    loadCities();
    loadCities2();
    $('#tableList').bootstrapTable({
        url: '/pigAccount/tableSearch',
        method: 'post',
        striped: true, //是否显示行间隔色
        toolbar: "#toolbar",
        sidePagination: "true",
        dataField: "data",//这是返回的json数组的key.默认是"rows".这里只有前后端约定好就行
        showToggle: true, //是否显示详细视图和列表视图的切换按钮
        striped: true, // 是否显示行间隔色
//search : "true",
        uniqueId: "id",
        pageList: [5, 10, 20, 50, 100],//可选择单页记录数
        pageSize: "10",
        pagination: true, // 是否分页
        sortable: true, // 是否启用排序
        sidePagination: 'server', // 设置为服务器端分页     客户端：client
        search: false,
        showColumns: true,
        showRefresh: true,
        showExport: true,
//得到查询的参数
        queryParams: function (params) {
//这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            var query_params = {
//********table的参数 不变
                pageSize: params.limit,                         //页面大小
                pageIndex: (params.offset / params.limit) + 1,   //页码
                sort: params.sort,      //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
//********
//获取查询的对象，往下加入
                timeInterval: $('#search_CarTime').val(), // 请求时向服务端传递的参数
            };
            return query_params;
        },
        columns: [
            {
//field: 'Number',//可不加
                title: '序号',//标题  可不加
                align: "center",
                width: 40,
                formatter: function (value, row, index) {
                    var pageSize = $('#tableList').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                    var pageNumber = $('#tableList').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                    return pageSize * (pageNumber - 1) + index + 1;//返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                }
            },
            // {field: 'readActivity', title: '是否已阅读温馨提示内容', align: 'center'},
            {field: 'recordNo', title: '生猪运输车辆备案号', align: 'center'},
            {
                field: 'recordForm', title: '生猪运输车辆备案表', align: 'center', width: 200,
                formatter: function (value) {
                    return "<a href='"+value+"' target='_blank'>查看图片</a>";
                    // return "<img src=\"" + value + "\" class=\"img-responsive\">";
                }
            },
            {field: 'carTime', title: '运载时间', align: 'center'},
            {field: 'proofCode', title: '检疫证明号码', align: 'center'},
            {field: 'pigNumber', title: '生猪头数', align: 'center'},
            {field: 'startFullAddress', title: '起运完整地址', align: 'center'},
            {field: 'farmerName', title: '养殖户名称', align: 'center'},
            {field: 'endFullAddress', title: '到达完整地址', align: 'center'},
            {field: 'route', title: '运载路径', align: 'center'},
            {field: 'startDisinfection', title: '装载前清洗消毒情况', align: 'center'},
            {field: 'endDisinfection', title: '装载后清洗消毒情况', align: 'center'},
            {field: 'disposal', title: '染疫、病死、死因不明生猪处置情况', align: 'center'},
            {field: 'remark', title: '备注', align: 'center'},
            {
                title: '操作',
                align: 'center',
                formatter: function (value, row, index) {
                    var optionHtml = "";
                    optionHtml = optionHtml + "<a class=\"btn btn-success btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"edit\")' title=\"修改\" ><i class=\"fa fa-edit\"></i>修改</a>";
                    optionHtml = optionHtml + " <a class=\"btn btn-danger btn-xs\" href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"delete\")'  title=\"删除\"><i class=\"fa fa-remove\"></i>删除</a>"
                    return optionHtml;

                }
            }
        ]
    });
}
//时间选择器**********
laydate.render({
    elem: '#text_carTime',
    theme: 'molv',
    type: "date",
});

laydate.render({
    elem: '#search_CarTime',
    range: true,
});

//查询方法****************************
function doSearch() {
// $('#tableList').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
    $("#tableList").bootstrapTable("refreshOptions", {pageNumber: 1});
}

//重置****************************
function doRest() {
    $("#search_CarTime").val("");
// $('#tableList').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
    $("#tableList").bootstrapTable("refreshOptions", {pageNumber: 1});
}

//增加方法****************************
var Action = "";
var id = 0;
var pxt = "/pigAccount"; //控制器名称
function addRecord() {
    id = 0;
    Action = "add";
    $("#myform")[0].reset();

}

//起运城市三级联动**************************
function loadCities() {
    $.ajax({
        url: "/city/tableSearch",
        type: "post",
        data: JSON.stringify({pageSize: 100}),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            initCitySelect(data.data);
            if (data.data[0]) {
                loadDistricts(data.data[0].city_id)
            }
        }
    });
}


function loadDistricts(city) {
    $.ajax({
        url: "/district/tableSearch",
        type: "post",
        data: JSON.stringify({city_id: $(city).val(), pageSize: 100}),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            initDistrictSelect(data.data);
            if (data.data[0]) {
                loadTowns(data.data[0].district_id)
            }
        }
    });
}


function loadTowns(district) {
    $.ajax({
        url: "/town/tableSearch",
        type: "post",
        data: JSON.stringify({district_id: $(district).val(), pageSize: 100}),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            initTownSelect(data.data);
        }
    });
}

function initCitySelect(data) {
    $('#text_startCity').empty();
    $.each(data, function (index, item) {
        $('#text_startCity').append("<option value='" + item.city_id + "'>" + item.city_name + "</option>");
    })
}

function initDistrictSelect(data) {
    $('#text_startDistrict').empty();
    $.each(data, function (index, item) {
        $('#text_startDistrict').append("<option value='" + item.district_id + "'>" + item.district_name + "</option>");
    })
}

function initTownSelect(data) {
    $('#text_startTownship').empty();
    $.each(data, function (index, item) {
        $('#text_startTownship').append("<option value='" + item.town_id + "'>" + item.town__name + "</option>");
    })
}

//到达城市三级联动**************************
function loadCities2() {
    $.ajax({
        url: "/city/tableSearch",
        type: "post",
        data: JSON.stringify({pageSize: 100}),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            initCitySelect2(data.data);
            if (data.data[0]) {
                loadDistricts2(data.data[0].city_id)
            }
        }
    });
}


function loadDistricts2(city) {
    $.ajax({
        url: "/district/tableSearch",
        type: "post",
        data: JSON.stringify({city_id: $(city).val(), pageSize: 100}),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            initDistrictSelect2(data.data);
            if (data.data[0]) {
                loadTowns2(data.data[0].district_id)
            }
        }
    });
}


function loadTowns2(district) {
    $.ajax({
        url: "/town/tableSearch",
        type: "post",
        data: JSON.stringify({district_id: $(district).val(), pageSize: 100}),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            initTownSelect2(data.data);
        }
    });
}

function initCitySelect2(data) {
    $('#text_endCity').empty();
    $.each(data, function (index, item) {
        $('#text_endCity').append("<option value='" + item.city_id + "'>" + item.city_name + "</option>");
    })
}

function initDistrictSelect2(data) {
    $('#text_endDistrict').empty();
    $.each(data, function (index, item) {
        $('#text_endDistrict').append("<option value='" + item.district_id + "'>" + item.district_name + "</option>");
    })
}

function initTownSelect2(data) {
    $('#text_endTownship').empty();
    $.each(data, function (index, item) {
        $('#text_endTownship').append("<option value='" + item.town_id + "'>" + item.town__name + "</option>");
    })
}

//增加/修改数据保存****************************
function saveRecord() {
    if (!validateForm()) return false;
//创建传递的参数
    var postdata = {
        id: id,
        action: Action,

        readActivity: $("#text_read").val(),
        recordNo: $("#text_recordNo").val(),
        recordForm: RecordForm,
        carTime: $("#text_carTime").val(),
        proofCode: $("#text_proofCode").val(),
        pigNumber: $("#text_pigNumber").val(),
        startProvince: $("#text_startProvince").val(),
        startCity: $("#text_startCity").val(),
        startDistrict: $("#text_startDistrict").val(),
        startTownship: $("#text_startTownship").val(),
        startDetailed: $("#text_startDetailed").val(),
        startFullAddress: $("#text_startProvince").find("option:selected").text() + $("#text_startCity").find("option:selected").text() + $("#text_startDistrict").find("option:selected").text() + $("#text_startTownship").find("option:selected").text() + $("#text_startDetailed").val(),
        farmerName: $("#text_farmerName").val(),
        endProvince: $("#text_endProvince").val(),
        endCity: $("#text_endCity").val(),
        endDistrict: $("#text_endDistrict").val(),
        endTownship: $("#text_endTownship").val(),
        endDetailed: $("#text_endDetailed").val(),
        endFullAddress: $("#text_endProvince").find("option:selected").text() + $("#text_endCity").find("option:selected").text() + $("#text_endDistrict").find("option:selected").text() + $("#text_endTownship").find("option:selected").text() + $("#text_endDetailed").val(),
        route: $("#text_route").val(),
        startDisinfection: $("#text_startDisinfection").val(),
        endDisinfection: $("#text_endDisinfection").val(),
        disposal: $("#text_disposal").val(),
        remark: $("#text_remark").val(),
    };
// console.log(JSON.stringify(postdata));
//发送异步请求到后台保存用户数据
    $.ajax({
        url: pxt + (Action == "add" ? "/save" : "/update"),
        type: "post",
        data: JSON.stringify(postdata),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            if (data.code === "200") {
                $('#myModalAdd').modal('hide')
                doSearch();
                swal("操作成功!", "请继续操作", "success");
            } else {
                swal("操作失败!", "请重试", "error");
            }
        }
    });
}

//操作相关方法****************************
function actionRecord(data, type) {
    HttpRecordForm = data.recordForm;
    if (type == "edit") {
//修改
        id = data.id;
        Action = "edit";
        $("#myform")[0].reset();
        $("#save").removeAttr("disabled");
        WriteData(data)
        $('#myModalAdd').modal('show')
    } else {
//删除
        swal({
            title: "确认是否删除",
            text: "是否确认要删除该条记录？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "删除",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function () {
//点击删除之后此处进行传递后台
            $.ajax({
                type: "delete",
                url: pxt + "/deleteById/" + data.id,
                dataType: "json",
                contentType: "application/json",
                success: function (data, status) {
                    if (data.code == "200") {
                        doSearch();
                        swal("删除成功!", "请继续操作", "success");
                    } else {
                        swal("删除失败!", "请重试", "error");
                    }
                }
            });

        });
    }
}

//给控件赋值****************************
function WriteData(data) {
    $("#text_read").val(data.readActivity);
    $("#text_recordNo").val(data.recordNo);
    var strs = data.recordForm.split("/");
    var str = strs[strs.length - 1];
    RecordForm = str;
    document.getElementById("showImage").style.display = "block";
    $("#showImage").attr("src", HttpRecordForm);
    $("#text_carTime").val(data.carTime);
    $("#text_proofCode").val(data.proofCode);
    $("#text_pigNumber").val(data.pigNumber);
    $("#text_startProvince").val(data.startProvince);
    $("#text_startCity").val(data.startCity);
    $("#text_startDistrict").val(data.startDistrict);
    $("#text_startTownship").val(data.startTownship);
    $("#text_startDetailed").val(data.startDetailed);
    $("#text_farmerName").val(data.farmerName);
    $("#text_endProvince").val(data.endProvince);
    $("#text_endCity").val(data.endCity);
    $("#text_endDistrict").val(data.endDistrict);
    $("#text_endTownship").val(data.endTownship);
    $("#text_endDetailed").val(data.endDetailed);
    $("#text_route").val(data.route);
    $("#text_startDisinfection").val(data.startDisinfection);
    $("#text_endDisinfection").val(data.endDisinfection);
    $("#text_disposal").val(data.disposal);
    $("#text_remark").val(data.remark);
}

//备案表图片
var RecordForm = "";
//备案表完整路径
var HttpRecordForm = ""

//上传****************************
function ImportShipmentStatusList() {
    console.log("进入图片上传方法")
    var upname = "text_recordForm";
    if ($("#" + upname).val() == "") {
        alert("请选择上传图片");
        return;
    }
    $.ajaxFileUpload({
        url: pxt + '/uploadImages',
        secureuri: false,
        fileElementId: upname,
        dataType: 'json',
        success: function (data, status) {
            RecordForm = data.url;
            HttpRecordForm = data.httpUrl;
            getImage(data.httpUrl);
            //隐藏文件选择
            $("#uploadImages").css("display", "none");
            //图片回显
            $("#showImage").css("display", "");
            $("#showImage").attr("src", data.httpUrl);
        },
        error: function (data, status, e) {
            console.log("上传图片失败", e);
        }
    });
}

function getImage(url) {
    var html = "";
    // html=html+"<div class=\"row\">";
    html = html + "<div class=\"col-lg-9\">";
    html = html + "<div class=\"form-group\" style='width:420px; height:250px'>";
    html = html + "<img style='width:420px; height:250px' src=\"" + url + "\" />";
    html = html + "<span class=\"label label-danger pull-right\" style=\"cursor:pointer\" onclick=\"delimage();\">删除</span>";
    html = html + "</div>";
    html = html + "</div>";
    html = html + "</div>";
}

function delimage() {
    //清空file
    var test = document.getElementById('text_image');
    test.value = '';
}

//表单验证*****************************
function validateForm() {
//validate方法参数可选
    return $("#myform").validate({
        rules: {

            text_read: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_recordNo: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_carTime: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_proofCode: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_pigNumber: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_startProvince: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_startCity: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_startDistrict: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_startTownship: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_startDetailed: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_farmerName: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_endProvince: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_endCity: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_endDistrict: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_endTownship: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_endDetailed: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_route: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_startDisinfection: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_endDisinfection: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_disposal: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
        },
//错误信息提示
        messages: {
            text_read: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_recordNo: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_carTime: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_proofCode: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_pigNumber: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_startProvince: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_startCity: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_startDistrict: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_startTownship: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_startDetailed: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_farmerName: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_endProvince: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_endCity: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_endDistrict: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_endTownship: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_endDetailed: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_route: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_startDisinfection: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_endDisinfection: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_disposal: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
        },
    }).form();

}
